<template>
  <div class="protype-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>工序分类管理</h2>
      <p>工序分类信息查询与管理</p>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="processTypeCode" label="工序分类编码" width="150">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">
              {{ row.processTypeCode }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="processTypeName" label="工序分类名称" width="200" />
        <el-table-column prop="processTypeState" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.processTypeState === 1 ? 'success' : 'danger'">
              {{ row.processTypeState === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleDetail(row)" class="action-btn">
                <el-icon><View /></el-icon>
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[6, 10, 20, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>


    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="工序分类详情"
      width="600px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工序分类编码">
            <el-tag type="primary">{{ currentDetail.processTypeCode }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工序分类名称">
            <el-tag type="info">{{ currentDetail.processTypeName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentDetail.processTypeState === 1 ? 'success' : 'danger'">
              {{ currentDetail.processTypeState === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View } from '@element-plus/icons-vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

// 使用正确的客户端 - 工序分类使用相对路径通过Vite代理
const r3 = getReadClient(0) // 使用相对路径，通过Vite代理到localhost:5154
const w8 = getWriteClient(0) // 使用相对路径，通过Vite代理到localhost:5070

// 接口类型定义
interface ProcessType {
  id: number
  processTypeCode: string
  processTypeName: string
  processTypeState: number
  isDelete: boolean
}

interface ApiResponse {
  data: {
    totalCount: number
    totalPage: number
    data: ProcessType[]
  }
  code: number
  message: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<ProcessType[]>([])

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<ProcessType | null>(null)

// 表单相关
const formData = reactive({
  processTypeCode: '',
  processTypeName: '',
  processTypeState: 1,
  isDelete: false
})

const formRef = ref()
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentEditId = ref<number | null>(null)
const submitLoading = ref(false)



// 分页数据
const pagination = reactive({
  pageindex: 1,
  pagesize: 6,
  totalCount: 0,
  totalPage: 0
})


// 获取工序分类列表数据
const fetchProcessTypeList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize
    }

    console.log('API请求参数:', params)
    console.log('使用的客户端:', r3.defaults.baseURL)
    
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Processs/processtypelist', { params })
    
    if (response.data.code === 200) {
      tableData.value = response.data.data.data
      pagination.totalCount = response.data.data.totalCount
      pagination.totalPage = response.data.data.totalPage
      console.log('获取到的数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取工序分类列表失败')
    }
  } catch (error: any) {
    console.error('获取工序分类列表失败:', error)
    ElMessage.error(`网络请求失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}


// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchProcessTypeList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchProcessTypeList()
}

// 查看详情
const handleDetail = (row: ProcessType) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentDetail.value = null
}



// 重置表单
const resetForm = () => {
  formData.processTypeCode = ''
  formData.processTypeName = ''
  formData.processTypeState = 1
  formData.isDelete = false
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  isEdit.value = false
  currentEditId.value = null
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    submitLoading.value = true
    
    // 准备提交数据
    const submitData: any = {
      processTypeCode: formData.processTypeCode,
      processTypeName: formData.processTypeName,
      processTypeState: formData.processTypeState,
      isDelete: formData.isDelete
    }
    
    // 如果是编辑模式，添加ID
    if (isEdit.value && currentEditId.value) {
      submitData.id = currentEditId.value
    }
    
    console.log('提交数据:', submitData)
    
    let response
    if (isEdit.value) {
      // 调用编辑接口
      response = await w8.post('/sellwriteapi/api/Processs/processtypeupdate', submitData)
    } else {
      // 调用新增接口
      response = await w8.post('/sellwriteapi/api/Processs/processtypeadd', submitData)
    }
    
    console.log('API响应:', response.data)
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '工序分类修改成功' : '工序分类新增成功')
      dialogVisible.value = false
      resetForm()
      // 刷新列表
      fetchProcessTypeList()
    } else {
      ElMessage.error(response.data.message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error: any) {
    console.error(isEdit.value ? '修改失败:' : '新增失败:', error)
    
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
      ElMessage.error(`服务器错误 (${error.response.status}): ${error.response.data?.message || '请检查后端服务是否正常运行'}`)
    } else if (error.request) {
      console.error('请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
  } finally {
    submitLoading.value = false
  }
}



// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取数据...')
  console.log('使用的客户端基础URL:', r3.defaults.baseURL)
  fetchProcessTypeList()
})
</script>

<style scoped>
.protype-list {
  padding: 0;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h2 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin: 0;
}

.action-card {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  padding: 12px 0;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 13px;
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8f4fd 100%);
  color: #606266;
  font-weight: 600;
  font-size: 12px;
  padding: 8px 0;
  border: none;
}

:deep(.el-table td) {
  padding: 8px 0;
  border-bottom: 1px solid #f0f2f5;
}

:deep(.el-table tbody tr:hover) {
  background-color: #f8f9fa;
}

:deep(.el-table tbody tr:last-child td) {
  border-bottom: none;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 16px;
}

/* 导出按钮样式 */
:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-button--success:focus) {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 详情页面样式 */
.detail-content {
  padding: 16px 0;
}

:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-tag) {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
}

/* 新增对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

/* 表单样式 */
.protype-form {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

/* 对话框按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.dialog-footer .el-button) {
  border-radius: 4px;
  padding: 8px 20px;
}

/* 操作按钮美化样式 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
  padding: 2px 0;
}

.action-btn {
  width: 65px;
  height: 26px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
  padding: 0 6px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

.action-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 详情按钮样式 */
.action-btn.el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border: none;
  color: white;
}

.action-btn.el-button--primary:hover {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
}

/* 编辑按钮样式 */
.action-btn.el-button--success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: white;
}

.action-btn.el-button--success:hover {
  background: linear-gradient(135deg, #85ce61 0%, #67c23a 100%);
}

/* 删除按钮样式 */
.action-btn.el-button--danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  border: none;
  color: white;
}

.action-btn.el-button--danger:hover {
  background: linear-gradient(135deg, #f78989 0%, #f56c6c 100%);
}

/* 按钮图标样式 */
.action-btn .el-icon {
  margin-right: 3px;
  font-size: 12px;
}

/* 表格操作列样式优化 */
:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-table .el-table__cell:last-child) {
  background-color: #fafbfc;
}

/* 分页组件样式优化 */
:deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

:deep(.el-pagination .el-pagination__total) {
  color: #606266;
  font-weight: 500;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 28px;
  height: 28px;
  line-height: 28px;
}

:deep(.el-pagination .el-pager li:hover) {
  background-color: #f5f7fa;
  color: #409eff;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: white;
  border: none;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 28px;
  height: 28px;
}

:deep(.el-pagination .btn-prev:hover),
:deep(.el-pagination .btn-next:hover) {
  background-color: #f5f7fa;
  color: #409eff;
}
</style>
